package com.zs.myorm.framework.core.execute.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import com.zs.myorm.framework.core.execute.ISqlExecute;

public class DefaultSqlExecuteImpl implements ISqlExecute {
	private DataSource dataSource;

	public DefaultSqlExecuteImpl(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	public int insert(String sql, Object... objects) {
		return updata(sql, objects);
	}

	@Override
	public List<Map<String, Object>> select(String sql, Object... objects) {
		try (Connection con = dataSource.getConnection();) {
			PreparedStatement stat = con.prepareStatement(sql);
			if (objects != null && objects.length > 0) {
				for (int i = 0; i < objects.length; i++) {
					stat.setObject(i + 1, objects[i]);
				}
			}
			ResultSet rs = stat.executeQuery();
			ResultSetMetaData metaData = rs.getMetaData();
			int columnCount = metaData.getColumnCount();
			String[] columns = new String[columnCount];
			for (int i = 0; i < columnCount; i++) {
				columns[i] = metaData.getColumnName(i + 1);
			}
			List<Map<String, Object>> reList = new ArrayList<Map<String, Object>>();
			while (rs.next()) {
				Map<String, Object> map = new HashMap<String, Object>();
				for (String col : columns) {
					map.put(col, rs.getObject(col));
				}
				reList.add(map);
			}
			return reList;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ArrayList<Map<String, Object>>();
	}

	public int updata(String sql, Object... objects) {
		// TODO Auto-generated method stub
		return 0;
	}

	public int delete(String sql, Object... objects) {
		return updata(sql, objects);
	}

}
